<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
</head>
<body>
    <button>发送</button>
    <button>取消</button>

    <script>
        //声明变量
        let cancel;
        //声明 CancelToken 函数
        function CancelToken(executor){
            //声明一个变量
            var resolvePromise;
            //声明一个属性
            this.promise = new Promise((resolve) => {
                resolvePromise = resolve;
            });
            //执行执行器函数
            executor(function(){
                resolvePromise();
            })
        }

        //发送请求
        function axios(config){
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                //初始化
                xhr.open(config.method, config.url);
                //发送
                xhr.send();
                //结果处理
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4) {
                        if(xhr.status >= 200 && xhr.status < 300){
                            //成功
                            resolve({
                                status: xhr.status,
                                statusText: xhr.statusText,
                                headers: xhr.getAllResponseHeaders(),
                                data: xhr.response,
                                request: xhr
                            });
                        }else{
                            //失败
                            reject(xhr.status);
                        }
                    }
                }
                //关于取消
                if(config.cancelToken){
                    config.cancelToken.promise.then(value => {
                        xhr.abort();
                    });
                }
            })
        }

        let btns = document.querySelectorAll('button');

        //点击事件
        btns[0].onclick = function(){
            //声明 cancelToken 对象
            let cancelToken = new CancelToken(function(c){
                cancel = c;
            });
            axios({
                url:'http://127.0.0.1/delay-server',
                method:'GET',
                cancelToken: cancelToken
            }).then(response => {
                console.log(response);
            }, error => {
                console.error(error);
            });
        }

        btns[1].onclick = function(){
            //3. 调用 cancel 函数即可
            cancel();
        }

       
    </script>
</body>
</html>